<template>
    <div class="order-approve">
        <!-- 页面切换下拉框 -->
        <div class="page-switch">
            <el-select v-model="currentPage" @change="handlePageChange">
                <el-option label="发起流程" value="traderOrder"></el-option>
                <el-option label="审批流程" value="orderApprove"></el-option>
            </el-select>
        </div>

        <!-- 审批流程标签页 -->
        <div class="approve-tabs">
            <el-tabs v-model="param.orderStatus" @tab-click="handleTabClick">
                <el-tab-pane label="全部订单" name="all"></el-tab-pane>
                <el-tab-pane label="待经理审批订单" name="0"></el-tab-pane>
                <el-tab-pane label="待总监审批订单" name="-1"></el-tab-pane>
                <el-tab-pane label="已审批订单" name="-2"></el-tab-pane>
                <el-tab-pane label="不通过订单" name="2"></el-tab-pane>
            </el-tabs>
        </div>

        <!-- 操作按钮区域 -->
        <div class="operation-bar">
            <el-button-group>
                <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加</el-button>
                <el-button icon="el-icon-download">导入</el-button>
                <el-button icon="el-icon-upload2">导出</el-button>
                <el-button icon="el-icon-delete" :disabled="!selectedRows.length"
                    @click="handleBatchDelete">删除</el-button>
                <el-button icon="el-icon-document">操作记录</el-button>
            </el-button-group>
        </div>

        <!-- 订单列表 -->
        <el-table :data="orderList" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="审批结果" width="100">
                <template slot-scope="scope">
                    <el-tag :type="getStatusType(scope.row.orderStatus)">
                        {{ getStatusText(scope.row.orderStatus) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="id" label="订单编码" width="150"></el-table-column>
            <el-table-column prop="distributorId" label="分销商编码" width="150"></el-table-column>
            <el-table-column prop="distributorName" label="分销商名称"></el-table-column>
            <el-table-column prop="paymentMethod" label="付款方式" width="120"></el-table-column>
            <el-table-column prop="totalPrice" label="商品总价值(元)" width="120"></el-table-column>
            <el-table-column prop="createdAt" label="创建时间" width="180"></el-table-column>
            <el-table-column prop="createdBy" label="申请人" width="120"></el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
                <template slot-scope="scope">
                    <el-button type="text" @click="showDetail(scope.row)">
                        查看详情
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[5, 10, 30, 50]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>

        <!-- 详情弹窗 -->
        <el-dialog title="订单详情" :visible.sync="dialogVisible" width="60%">
            <div v-if="currentRow" v-loading="detailLoading">
                <el-descriptions :column="2" border>
                    <el-descriptions-item label="订单ID">{{ detailInfo.id }}</el-descriptions-item>
                    <el-descriptions-item label="订单编号">{{ detailInfo.code }}</el-descriptions-item>

                    <el-descriptions-item label="分销商名称">{{ detailInfo.distributorName }}</el-descriptions-item>
                    <el-descriptions-item label="分销商电话">{{ detailInfo.distributorPhone }}</el-descriptions-item>

                    <el-descriptions-item label="分销商联系人">{{ detailInfo.distributorContact }}</el-descriptions-item>
                    <el-descriptions-item label="订单日期">{{ detailInfo.orderDate }}</el-descriptions-item>

                    <el-descriptions-item label="销售订单编号">{{ detailInfo.salesOrderCode }}</el-descriptions-item>
                    <el-descriptions-item label="销售负责人">{{ detailInfo.salesManager }}</el-descriptions-item>

                    <el-descriptions-item label="商品名称" :span="2">{{ detailInfo.allProductNames }}</el-descriptions-item>

                    <el-descriptions-item label="订单原价">{{ detailInfo.totalOriginalPrice }} 元</el-descriptions-item>
                    <el-descriptions-item label="优惠金额">{{ detailInfo.discountAmount }} 元</el-descriptions-item>

                    <el-descriptions-item label="订单申请人">{{ detailInfo.orderApplicant }}</el-descriptions-item>
                    <el-descriptions-item label="订单状态">
                        <el-tag :type="getStatusType(detailInfo.orderStatus)">
                            {{ getStatusText(detailInfo.orderStatus) }}
                        </el-tag>
                    </el-descriptions-item>

                    <el-descriptions-item label="创建人">{{ detailInfo.createdBy }}</el-descriptions-item>
                    <el-descriptions-item label="创建时间">{{ detailInfo.createdAt }}</el-descriptions-item>
                </el-descriptions>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'OrderApprove',
    data() {
        return {
            currentPage: 'orderApprove',
            pageNum: 1,
            pageSize: 5,
            total: 0,
            orderList: [],
            selectedRows: [],
            dialogVisible: false,
            currentRow: null,
            param: {
                orderStatus: ''
            },
            detailInfo: {},
            detailLoading: false,
        }
    },
    methods: {
        handlePageChange(value) {
            if (value === 'traderOrder') {
                this.$router.push('/order/traderOrder')
            } else if (value === 'orderApprove') {
                this.$router.push('/order/orderApprove')
            }
        },
        handleAdd() {
            this.$router.push('/order/traderOrder')
        },
        handleSizeChange(val) {
            this.pageSize = val
            this.pageNum = 1
            this.fetchData()
        },
        handleCurrentChange(val) {
            this.pageNum = val
            this.fetchData()
        },
        fetchData() {
            const pageParam = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                param: this.param
            };

            this.$axios.post('api/order-server/zfOrder/queryAllPage', pageParam)
                .then(resp => {
                    if (resp.data.code === 200) {
                        this.orderList = resp.data.data.list
                        this.total = resp.data.data.total
                    } else {
                        this.$message.error(resp.data.message || '获取数据失败')
                    }
                })
                .catch(error => {
                    console.error('获取数据失败:', error)
                    this.$message.error('获取数据失败')
                })
        },
        // 表格多选
        handleSelectionChange(val) {
            this.selectedRows = val
        },
        // 查看详情
        showDetail(row) {
            this.currentRow = row;
            this.dialogVisible = true;
            this.getOrderDetail(row.id);
        },
        // 获取订单详情
        getOrderDetail(id) {
            // 开始加载
            this.detailLoading = true;

            // 创建一个 URLSearchParams 对象来传递 URL 参数
            const params = new URLSearchParams();
            params.append('id', id);  // 将 id 添加到参数中

            // 使用 POST 请求，传递 id 参数
            this.$axios.post('api/order-server/zfOrder/queryById', params)
                .then(response => {
                    // 如果后端返回 code 为 200，表示请求成功
                    if (response.data.code === 200) {
                        // 将返回的数据存储到 detailInfo 中，供页面使用
                        this.detailInfo = response.data.data;
                    } else {
                        // 如果请求失败，显示错误信息
                        this.$message.error(response.data.message || '获取详情失败');
                    }
                })
                .catch(() => {
                    // 捕捉异常，显示网络请求失败的信息
                    this.$message.error('获取详情失败');
                })
                .finally(() => {
                    // 不管请求成功还是失败，都停止加载
                    this.detailLoading = false;
                });
        },

        // 批量删除
        handleBatchDelete() {
            this.$confirm('确认删除选中的记录?', '提示', { type: 'warning' })
                .then(() => {
                    const ids = this.selectedRows.map(({ id }) => id);

                    return this.$axios.post('api/order-server/zfOrder/batchDel', ids);
                })
                .then(({ data }) => {
                    const { code, message } = data;
                    if (code === 200) {
                        this.$message.success('删除成功');
                        this.fetchData(); // 重新加载数据
                    } else {
                        this.$message.error(message || '删除失败');
                    }
                })
                .catch(() => {
                    this.$message.error('删除失败');
                });
        },

        // 获取表格数据
        getTableData() {
            // 这里写您的数据加载逻辑
        },
        getStatusType(status) {
            const statusMap = {
                '-2': 'warning',   // 已审批
                '-1': 'warning',   // 经理已审批
                '0': 'info',       // 总监已审批
                '1': 'success',    // 已完成
                '2': 'primary',    // 已发货
                '3': 'danger'      // 已删除
            }
            return statusMap[status] || 'info'
        },
        getStatusText(status) {
            const statusMap = {
                '-2': '已审批（2/2）',
                '-1': '待审批（1/2）',
                '0': '待审批（0/2）',
                '1': '已完成',
                '2': '已发货',
                '3': '已删除'
            }
            return statusMap[status] || '未知状态'
        },
        // 处理标签页切换
        handleTabClick() {
            // 如果是全部订单，把orderStatus设为空
            if (this.param.orderStatus === 'all') {
                this.param.orderStatus = '';
            }
            this.fetchData();
        },
    },
    mounted() {
        this.fetchData();
    }
}
</script>

<style scoped>
.order-approve {
    padding: 20px;
    background-color: #f5f7fa;
}

.page-switch {
    margin-bottom: 20px;
}

.page-switch .el-select {
    width: 200px;
}

.approve-tabs {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
}

.operation-bar {
    margin-bottom: 20px;
    background: #fff;
    padding: 15px;
    border-radius: 4px;
}

.pagination-container {
    text-align: right;
    margin-top: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 4px;
}

.el-table {
    margin-top: 20px;
}

.el-dialog__body {
    padding: 20px;
}
</style>